using System;
using System.Collections;
using System.Collections.Generic;
using DailyReport.Core.Data.Dao;
using DailyReport.Core.Data.Model;
using DailyReport.Core.Util;
using NHibernate;

namespace DailyReport.NHibernateDao.Data.Dao
{
    public class TeamDao: NHibernateBaseDao<Team, int>, ITeamDao
    {
        
        public TeamDao()
        {
        }

        Team IGenericDao<Team, int>.GetById(int id, bool shouldLock)
        {
            ISession session = ConnectionManager.Instance.CurrentFactory.OpenSession();
            
            Team res=new Team();
            ITransaction transaction = session.BeginTransaction();
            session.Load(res, id);
            transaction.Commit();
            session.Close();
            return (res);
        }

        List<Team> IGenericDao<Team, int>.GetAll()
        {
            List<Team> res=new List<Team>();
            ISession session = ConnectionManager.Instance.CurrentFactory.OpenSession();
            ITransaction transaction = session.BeginTransaction();
            
            res = (List<Team>)session.GetNamedQuery("allTeamsQuery");
            
            transaction.Commit();
            session.Close();
            return (res);
        }

        
        public IList getInstancesList(string sortExpression,int maxRows, int startRowIndex)
        {
            log.Warn("****#TEAMDAO.getInstancesList METHOD");
            String queryStr = "from Team";
            ISession session = ConnectionManager.Instance.CurrentFactory.OpenSession();
            if (sortExpression != null && sortExpression.Length > 0)
                queryStr = queryStr + " order by " + sortExpression;
            log.Warn("****#La consulta: "+queryStr+" startRowIndex="+startRowIndex+" maxRows="+maxRows);
            IQuery querySorteable = session.CreateQuery(queryStr)
                                           .SetFirstResult(startRowIndex)
                                           .SetMaxResults(maxRows);
            IList res = (IList) querySorteable.List();
            session.Close();
            return (res);
        }
        public int getInstancesCount()
        {
            log.Warn("****#TEAMDAO.getInstancesCount METHOD");
            int res;
            ISession session = ConnectionManager.Instance.CurrentFactory.OpenSession();
            ITransaction transaction = session.BeginTransaction();
            res = (int)session.GetNamedQuery("teamsCountQuery")
                             .SetMaxResults(1)
                             .UniqueResult();

            transaction.Commit();
            session.Close();
            return (res);
        }
    }
}
